<template>
	<div class="app-container">
		<el-form :inline="true" ref="queryRef" label-position="right" :model="params" label-width="200px">
			<div class="form-inline">
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="区域：" class="form-item" prop="province">
							<el-form-item prop="province" style="width: 120px; margin-right: 10px">
								<el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince"
									value-key="id">
									<el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="city" style="width: 120px; margin-right: 10px">
								<el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
									value-key="id">
									<el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="county" style="width: 120px">
								<el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable
									value-key="id">
									<el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item">
									</el-option>
								</el-select>
							</el-form-item>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="数据类别：" class="form-item" prop="dataType">
							<el-select v-model="params.dataType" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in dataCategoryOptions" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="结构类型：">
							<el-col :span="12">
								<el-form-item prop="structureType">
									<el-select v-model="params.structureType" placeholder="请选择" class="form-select"
										@change="structureTypeChange" clearable>
										<el-option v-for="item in structureTypeOptions" :key="item.value"
											:label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center">
								<span class="text-gray-500">-</span>
							</el-col>
							<el-col :span="11">
								<el-form-item prop="structureType1">
									<el-select v-model="params.structureType1" placeholder="请选择" class="form-select"
										clearable>
										<el-option v-for="item in structureType1Options" :key="item.value"
											:label="item.label" :value="item.value">
										</el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
					<el-col :span="11"></el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="维护人：" class="form-item" prop="userName" >
							<el-input v-model="params.userName" placeholder="请输入" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="维护时间:">
							<el-col :span="11">
								<el-form-item prop="createStartTime">
									<el-date-picker clearable v-model="params.createStartTime" type="date"
										placeholder="开始时间" value-format="YYYY-MM-DD" :disabled-date="startDisableDate"
										style="width: 100%" />
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center">
								<span class="text-gray-500">-</span>
							</el-col>
							<el-col :span="11">
								<el-form-item prop="createEndTime">
									<el-date-picker clearable v-model="params.createEndTime" type="date" placeholder="结束时间"
										value-format="YYYY-MM-DD" :disabled-date="endDisableDate" style="width: 100%" />
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<!-- <el-col :span="11">
						<el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit">
							<el-input v-model="params.maintainerUnit" placeholder="" clearable />
						</el-form-item>
					</el-col> -->
					<el-col :span="11">
						<el-form-item label="设防情况：" class="form-item" prop="fortification">
							<el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="建造年代：" class="form-item" prop="years">
							<el-select v-model="params.years" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="是否在基础库：" class="form-item" prop="basicLibrary" v-show="isAdmin">
							<el-select v-model="params.basicLibrary" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in basicLibraryOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11"></el-col>
				</el-row>
				<el-row justify="end">
					<el-form-item class="bottom-button">
						<el-button type="primary" @click="onImportArchive">移入管理库</el-button>
						<el-button type="primary" @click="onImport">导入</el-button>
						<el-button type="primary" @click="onSearch">查询</el-button>
						<el-button type="primary" @click="onRest">重置</el-button>
					</el-form-item>
				</el-row>
			</div>
		</el-form>

		<div class="table-wrapper">
			<el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
				@selection-change="handleSelectionChange" :cell-style="{ border: '1px solid #e5ebf7' }"
				:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }" row-key="id">
				<el-table-column :reserve-selection="true" type="selection" width="55" label="序号" />
				<el-table-column prop="number" header-align="center" align="center" label="编号" width="160">
					<template #default="{ row }">
						<el-button link type="text" size="small" @click="handleDetail(row)">{{ row.number }}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="region" header-align="center" align="center" label="区域" width="180" />
				<el-table-column prop="st" header-align="center" align="center" label="结构类型" width="160" />
				<el-table-column prop="years" header-align="center" align="center" label="建造年代" width="160" />
				<el-table-column prop="fortification" header-align="center" align="center" label="设防情况" />
				<el-table-column prop="userName" header-align="center" align="center" label="维护人" />
				<el-table-column prop="createTime" header-align="center" align="center" label="维护时间" width="160" />
				<el-table-column prop="remarks" header-align="center" align="center" label="备注" />
				<el-table-column prop="basicLibrary" header-align="center" align="center" label="是否在基础库" v-if="isAdmin">
					<template #default="scope">
						{{ scope.row.basicLibrary == '1' ? '是' : '否' }}
					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" align="center" width="120" v-if="isAdmin">
					<template #default="{ row }">
						<el-button :type="row.basicLibrary && row.basicLibrary.trim() == '1' ? 'danger' : 'success'" text
							size="small" @click="handleRemove(row)">
							{{ row.basicLibrary && row.basicLibrary.trim() == '1' ? '移出管理库' : '移入管理库' }}
						</el-button>
					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" width="80">
					<template #default="scope">
						<el-button v-if="scope.row.basicLibrary != '1'" type="text" size="small"
							@click="onDelete(scope.row)">删除</el-button>
						<!-- <el-button type="text" size="small" @click="onModify(scope.row)">修改</el-button> -->
					</template>
				</el-table-column>
			</el-table>
			<div class="paging">
				<el-pagination background v-model:current-page="queryPagination.pageNo" :layout="layout"
					:page-size="queryPagination.pageSize" :total="queryPagination.total"
					@current-change="handleCurrentChange" @size-change="handleSizeChange" />
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, toRefs } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import { getProvince, getChildArea } from "@/api/system/division";
// 引入接口
import { getInfo } from '@/api/login'
import { getUserId } from "@/utils/auth";
import {
	queryBacInformation, //查询
	queryBacInformationById, //根据id查询
	updateBacInformation, //修改
	deleteBacInformation, //删除
	moveBasicLibraryApi, //移入/出基础库
	queryMoveBasicLibraryApi,
	exportExcelBvInfoApi, //导出易损性矩阵信息
} from "@/api/importData/buildingAreaInfo.js";
// 公用方法
import { downloadFile } from "@/utils/ruoyi.js";
// 状态管理模块
import useUserStore from "@/store/modules/user";
import useDictStore from '@/store/modules/dict';
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 是否管理员
const isAdmin = computed(() => userStore.isAdmin || false);

// 获取当前实例
const { proxy } = getCurrentInstance()
// 全局路由对象
const router = useRouter();

const data = reactive({
	// 表单参数
	params: {
		city: null,
		county: null,
		province: '',
		dataType: "", //数据类别
		// intensity: "", //烈度
		// damage: "", //破坏状态
		createStartTime: "", //维护开始时间
		createEndTime: "",//维护结束时间
		userName: "", //维护人
		structureType: "", //结构类型
		structureType1: "",
		maintainerUnit: "", //维护人所属单位
		fortification: "", //设防情况
		years: "",//建造年代
		basicLibrary: ''//是否在基础库
	},
	// 数据类别
	dataCategoryOptions: [
		{
			value: '建筑物易损性信息',
			label: '建筑物易损性信息'
		},
		{
			value: '砖混结构参数信息',
			label: '砖混结构参数信息'
		},
		{
			value: '钢筋混凝土参数信息',
			label: '钢筋混凝土参数信息'
		},
		{
			value: '高层建筑参数信息',
			label: '高层建筑参数信息'
		},
		// {
		// 	value: '概率地震易损性分析数据',
		// 	label: '概率地震易损性分析数据'
		// }
	],
	// 破坏状态
	// collapseStateOptions: dictStore.collapseStateOptions || [],
	// 烈度
	// intensityOptions: dictStore.intensityOptions || [],
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 建造年代
	yearsOptions: dictStore.yearsOptions || [],
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	//是否在基础库
	basicLibraryOptions: dictStore.basicLibraryOptions || [],
	//表格
	tableData: [],
	//分页
	layout: " prev, pager, next, jumper, sizes, total",
	queryPagination: {
		pageNo: 1,
		pageSize: 10,
		total: 100,
	},
})
const {
	params,
	dataCategoryOptions,
	// collapseStateOptions,
	// intensityOptions,
	fortificationOptions,
	yearsOptions,
	structureTypeOptions,
	structureType1Options,
	tableData,
	queryPagination,
	layout,
	//是否在基础库
	basicLibraryOptions
} = toRefs(data);

// 打开详情
const handleDetail = (row) => {
	if (row.dataType == '建筑物易损性信息') {
		router.push({
			path: '/disasterDataManagement/maintainData/buildingAreaInfoDetail', query: {
				id: row.id,
				number: row.number,
				dataType: row.dataType,
				province: row.region.split('-')[0],
			}
		});
	} else {
		exportExcelBvInfoApi({
			id: row.id,
			type: row.dataType,
		}).then(res => {
			if (res) {
				downloadFile(res, `${row.dataType || '建筑物易损数据'}${row.number ? '(' + row.number + ')' : ''}.xlsx`);
			} else {
				proxy.$modal.msgError('导出易建筑物损性数据失败！');
			}
		}).catch(err => {
			proxy.$modal.msgError(err || '导出建筑物易损性数据失败！');
		});
	}
}
//是否移出管理库
const handleRemove = (row) => {
	moveBasicLibraryApi([{
		dataType: row.dataType,
		operate: row.basicLibrary && row.basicLibrary.trim() == '1' ? 0 : 1,
		province: row.region.split('-')[0],
		...row,
	}]).then((res) => {
		if (res.code === 200) {
			if (res.data.length > 0&&row.basicLibrary=='0') {
				ElMessageBox.confirm(
					'建筑物易损性数据库中条件相同的数据，是否替换?',
					'消息',
					{
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning',
					}
				)
					.then(() => {
						// 确定移入
						queryMoveBasicLibraryApi({
							oldData:[{
								dataType: row.dataType,
								operate: row.basicLibrary && row.basicLibrary.trim() == '1' ? 0 : 1,
								province: row.region.split('-')[0],
								...row,
							}],
	 						newData: res.data }).then(response => {
							proxy.$modal.msgSuccess("成功");
							// 查询，更新列表
							onSearch();
						})
					})
					.catch(() => {
					})
			} else {
				proxy.$modal.msgSuccess("成功");
				// 查询，更新列表
				onSearch();
			}
		}
	}).catch(err => {
		console.log(err.message);
	});
}

// 时间可选区间控制
const startDisableDate = (time) => {
	let endDateVal = params.value.createEndTime
	if (endDateVal) {
		return time.getTime() > new Date(endDateVal).getTime()
	}
}
const endDisableDate = (time) => {
	let beginDateVal = params.value.createStartTime
	if (beginDateVal) {
		return time.getTime() < new Date(beginDateVal).getTime()
	}
}
// 选择结构类型
const structureTypeChange = (val) => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val)
	if (structureTypes) {
		structureType1Options.value = structureTypes.children
	}
	params.value.structureType1 = '';
	// 设防情况
	params.value.fortification = '';
	fortificationOptions.value = dictStore.fortificationOptions;
	// 年代
	yearsOptions.value = dictStore.yearsOptions;
	// 过滤楼层预选项
	if (val=='钢筋混凝土结构'||val=='钢结构') {
	} else if(val=='组合结构'){
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value!='未设防'&&item.value!='自设防'));
	}else if(val=='砌体结构'){
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions;
	}else{
		if(val=='土木结构'||val=='木结构'||val=='其他'){

		if(val=='土木结构'){
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>item.value=='未设防');
		yearsOptions.value = dictStore.yearsOptions.filter((item, index) => index < 4);
		// 切换类型时，年代--选项，则清空
		if (params.value.years == '2010-2016年'||params.value.years == '2016年以后') {
			params.value.years = ''
		}
		}else if(val=='其他'){
			fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value=='未设防'||item.value=='自设防'||item.value=='6度'));
		}
	}
	}
}
// 获取用户
function getUserInfo() {
	getInfo(getUserId()).then(response => {
		// params.value.userName = response.user.userName
		// params.value.maintainerUnit = response.user.orgName
		if (!isAdmin.value) {
			provinceData.value = provinceData.value.filter(item => item.id == response.user.provinceId);
		}
		params.value.province = provinceData.value.filter(item => item.id == response.user.provinceId)[0].name;
		chooseProvince({ id: response.user.provinceId, name: params.value.province })
	});
};

// 表格
const multipleTableRef = ref();
const multipleSelection = ref([]);
// 表格点击选择事件
const handleSelectionChange = (val) => {
	multipleSelection.value = val;
};
// 分页,每页显示多少条数据
const handleSizeChange = (val) => {
	// 改变每页显示的条数 
	queryPagination.value.pageSize = val;
	// 注意：在改变每页显示的条数时，要将页码显示到第一页
	queryPagination.value.pageNo = 1;
	// 查询
	onSearch();
};
// 分页,当前页数
const handleCurrentChange = (val) => {
	queryPagination.value.pageNo = val;
	// 查询
	onSearch();
};

//建筑物区域特征信息维护表格查询
const onSearch = () => {
	// 加载动画
	proxy.$modal.loading('加载中...');
	queryBacInformation({
		...params.value,
		page: queryPagination.value.pageNo,
		rows: queryPagination.value.pageSize
	}).then((res) => {
		// 关闭加载动画
		proxy.$modal.closeLoading();
		const { code, data } = res
		if (code == 200) {
			const { total, rows } = data;
			queryPagination.value.total = total
			tableData.value = rows || [];
		}
	}).catch(err => {
		// 关闭加载动画
		proxy.$modal.closeLoading();
		console.log(err);
	});
};
//重置
const onRest = () => {
	// 清空表单
	params.value = {
		province: params.value.province,
		city: null,
		county: null,
		dataType: "", //数据类别
		// intensity: "", //烈度
		// damage: "", //破坏状态
		createStartTime: "", //维护开始时间
		createEndTime: "",//维护结束时间
		// userName: "", //维护人
		structureType: "", //结构类型
		structureType1: "",
		// maintainerUnit: "", //维护人所属单位
		fortification: "", //设防情况
		years: "",//建造年代
		basicLibrary: ''//是否在基础库
	}
	queryPagination.value.pageNo = 1;
	// 查询
	onSearch();
};

// 批量移入数据库
const onImportArchive = () => {
	if (multipleSelection.value.length == 0) {
		proxy.$modal.msgWarning('请选择至少一条数据！！！')
	} else {
		let flag = multipleSelection.value.every(item => item.basicLibrary.trim() == '0')
		if (!flag) {
			proxy.$modal.msgWarning('请选择未移入管理库的数据！！！')
			return;
		}
		multipleSelection.value.forEach(item=>{
			item.operate = '1',
			item.province = item.region.split('-')[0]
		})
		moveBasicLibraryApi(multipleSelection.value).then((res) => {
			if (res.code === 200) {
				if (res.data.length > 0) {
					let msg = ''
					msg = res.data.map(item=>item.number)
					ElMessageBox.confirm(
						`编号${msg.join('、')}，建筑物易损性数据库中条件相同的数据，是否替换?`,
						'消息', 
						{
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning',
						}
					)
						.then(() => {
							// 确定移入
							queryMoveBasicLibraryApi({
								oldData:multipleSelection.value,
								newData:res.data
							}).then(response => {
								multipleTableRef.value.clearSelection()
								proxy.$modal.msgSuccess("成功");
								// 查询，更新列表
								onSearch();
							})
						})
						.catch(() => {
						})
				} else {
					multipleTableRef.value.clearSelection()
					proxy.$modal.msgSuccess("成功");
					// 查询，更新列表
					onSearch();
				}
			}
		}).catch(err => {
			console.log(err.message);
		});
	}
	// multipleSelection.value.filter(item=>item.id)
}

// 导入
const onImport = () => {
	router.push({ path: '/disasterDataManagement/importData/buildingAreaInfo' })
}
// 修改
// const onModify = (row) => {
//     router.push({ path: '', query: { id: 'modify', type: row.type } })
// }
// 删除
const onDelete = (row) => {
	proxy.$modal.confirm("请确定是否删除？").then(() => {
		deleteBacInformation({ ids: row.id, type: row.dataType ,province:row.region.split('-')[0]}).then((res) => {
			if (res.code === 200) {
				proxy.$modal.msgSuccess("删除成功");
				// 重新加载表格
				onSearch();
			}
		}).catch(err => {
			console.log(err.message);
		})
	})
}

// 行政区划
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
/** 获取省列表 */
function getProvinceData() {
	getProvince().then((response) => {
		provinceData.value = response.data;
		getUserInfo()
	});
}
// 选择省份
function chooseProvince(value) {
	params.value.city = null;
	params.value.county = null;
	params.value.province = value.name;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value.id).then((response) => {
		cityData.value = response.data;
	});
}
// 选择城市
function chooseCity(value) {
	params.value.city = value.name;
	params.value.county = null;
	areaData.value = [];
	getChildArea(value.id).then((response) => {
		areaData.value = response.data;
	});
}
// 选择区县
function chooseCounty(value) {
	params.value.county = value.name;
}
getProvinceData();
onMounted(() => {
	// 初始化获取数据
	setTimeout(() => {
		onSearch();
	}, 200)
});
</script>
 
<style lang="scss" scoped>
.paging {
	padding: 20px 0;
}

.form-inline {
	.el-form-item {
		margin-right: 0px;
	}
}
</style>
